import { _decorator,director, sys } from 'cc';
import Colyseus, { Room } from 'db://colyseus-sdk/colyseus.js';
import _ from 'lodash'
import { SceneFlag } from './SceneFlag';
const { ccclass, property } = _decorator;
/**
 * Predefined variables
 * Name = NetWorkManager
 * DateTime = Sat Feb 05 2022 15:08:58 GMT+0800 (中国标准时间)
 * Author = awi1299
 * FileBasename = NetWorkManager.ts
 * FileBasenameNoExtension = NetWorkManager
 * URL = db://assets/script/NetWorkManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */
export class NetWorkManager{
    private static instance: NetWorkManager;
    hostname = 'localhost'
    port = 3000;
    client: Colyseus.Client
    joinRoomId = ''
    isReconnect = false
    curScene:SceneFlag
    room: Room


    private constructor() {
        console.log(this.hostname)
        // game.addPersistRootNode(this.node)//常驻节点

        //连接服务端
        this.client = new Colyseus.Client(`ws://${this.hostname}:${this.port}`)


        console.log(new Date(sys.localStorage.getItem('storeTime')))
        console.log('start reconnect')
        const interTime = new Date().valueOf() - new Date(sys.localStorage.getItem('storeTime')).valueOf()
        console.log(`上次会话 ${_.round(interTime / 1000)} 秒前`)
        if(!this.canReconnect()){
            console.log(`上次会话已经失效`)
            return
        }
        this.isReconnect = true
        director.loadScene(SceneFlag.GAME)
    }

    static getInstance(): NetWorkManager{
        if(!NetWorkManager.instance)NetWorkManager.instance = new NetWorkManager()
        return NetWorkManager.instance
    }

    canReconnect(){
        const interTime = new Date().valueOf() - new Date(sys.localStorage.getItem('storeTime')).valueOf()
        if (interTime > 600 * 1e3) {
            return false
        }
        return true
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/zh/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/zh/scripting/life-cycle-callbacks.html
 */
